using IQIGame.Onigao.Game;

namespace IQIGame.Onigao.GamePlay
{
    /// <summary>
    /// 多媒体控制器，声音和视频等。
    /// </summary>
    public class LevelPlayMediaCtrl : LevelPlaySubBaseCtrl
    {
        public LevelPlayMediaCtrl()
        {
            MsgDispatcher.AddListener<int>(MsgEventType.Level_NotifyCustomBgmChange, NotifyCustomBgmChange);
            MsgDispatcher.AddListener(MsgEventType.Level_TriggerAreaChanged, RefreshLevelBGMPlay);
        }

        /// <summary>
        /// 更改BGM
        /// </summary>
        /// <param name="bgmAudioCid">大于0表示播放Audio表的BGM，等于0恢复默认场景播放，等于-1为不播放任何BGM</param>
        public void NotifyCustomBgmChange(int bgmAudioCid)
        {
            if (!regionCtrl.levelRegion.ChangeCustomBgm(bgmAudioCid))
            {
                return;
            }
            RefreshLevelBGMPlay();
        }

        public void RefreshLevelBGMPlay()
        {
            var bgmAudioCid = regionCtrl.levelRegion.customBgmCid;
            // 优先级：自定义BGM > triggerRect自定义区域BGM > 场景默认BGM
            switch (bgmAudioCid)
            {
                case 0:
                    // 恢复场景默认播放的BGM

                    // TriggerRect 区域BGM
                    var currentArea = regionCtrl.areaEffectCtrl.currentAreaParam;
                    if (currentArea != null && currentArea.bgmAudioCid > 0)
                    {
                        ManagerCenter.Audio.PlayAudioByIdAndCheckType(currentArea.bgmAudioCid, AudioSourceType.BgmSource);
                        return;
                    }

                    // 场景默认BGM
                    var sceneBgmId = regionCtrl.cfgRegionPack.cfgScene.BgmAudioId;
                    if (sceneBgmId > 0)
                    {
                        ManagerCenter.Audio.PlayAudioByIdAndCheckType(sceneBgmId, AudioSourceType.BgmSource);
                        return;
                    }

                    // 否则，不需要播放BGM
                    ManagerCenter.Audio.StopSource(AudioSourceType.BgmSource);

                    break;
                case -1:
                    // 停止播放
                    ManagerCenter.Audio.StopSource(AudioSourceType.BgmSource);
                    break;
                default:
                    //播放并且检测是否是BGM类型
                    ManagerCenter.Audio.PlayAudioByIdAndCheckType(bgmAudioCid, AudioSourceType.BgmSource);
                    break;
            }
        }

        #region 生命周期
        protected override void OnModuleGameplayInit()
        {

        }

        protected override void OnSceneLoaded()
        {
            // 初始化BGM播放
            RefreshLevelBGMPlay();
        }

        protected override void OnDispose()
        {
            ManagerCenter.Audio.StopSource(AudioSourceType.BgmSource);
            MsgDispatcher.RemoveListener<int>(MsgEventType.Level_NotifyCustomBgmChange, NotifyCustomBgmChange);
            MsgDispatcher.RemoveListener(MsgEventType.Level_TriggerAreaChanged, RefreshLevelBGMPlay);
        }
        #endregion

    }
}
